package tech.aistar.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tech.aistar.mapper.UserMapper;
import tech.aistar.pojo.User;
import tech.aistar.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    @Override
    public User getByEmail(String email) {
        return userMapper.getByEmail(email);
    }

    @Async //异步任务
    @Override
    public void sendCode(String email) {
        //TODO... 发送验证码的逻辑
        //1. 封装邮件的各个信息的
        SimpleMailMessage msg = new SimpleMailMessage();
        //邮件的发送方,此处的邮箱必须是application.yml中设置的邮箱
        msg.setFrom("2357511052@qq.com");
        //设置邮件的标题
        msg.setSubject("青岛科技验证码");

        //随机生成一个[100000,999999]之间的6位的随机整数
        String code = String.format("%06d", (int)(Math.random()*900000)+100000);

        //设置邮件的正文内容
        msg.setText("验证码:+"+code);

        redisTemplate.opsForValue().set(email, code,30, TimeUnit.MINUTES);

        //邮件的接收方 - 是可以随便写的
        msg.setTo(email);

        //发送
        mailSender.send(msg);
    }

    @Override
    public PageInfo<User> pageInfo(Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<User> list=userMapper.findAll();
        PageInfo<User> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<User> listAll() {
        //TODO... 如果业务逻辑比较简单的话,那么此处是直接调用mapper里面的findAll方法
        List<User> users = userMapper.findAll();
        //TODO... 可能对所有的users比如进行排序的操作,只是暂时没有而已
        return users;
    }

    @Override
    public User getById(Integer id) {
        User user = userMapper.getById(id);
        return user;
    }

    @Override
    public int delById(Integer id) {
        return userMapper.delById(id);
    }

}
